package top.ljlgithub.api.common.handler;

import com.auth0.jwt.exceptions.JWTCreationException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.ljlgithub.api.common.response.Meta;
import top.ljlgithub.api.common.response.ResponseEntity;
import top.ljlgithub.api.exception.ParamException;
import top.ljlgithub.api.exception.RightException;

/**
 * @ClassName
 * @Description TODO
 * @Author L1470
 * @Date 2021/4/25 19:45
 * @Version 1.0
 **/
//设置全局的异常过滤器，通过Advice这个注解，捕捉到什么异常就执行对应的方法返回信息和状态值
@RestControllerAdvice
public class GlobalExceptionHandler {
    //这种设计方式是为了防止用户信息泄露。
    @ExceptionHandler({IncorrectCredentialsException.class,UnknownAccountException.class})
    public ResponseEntity handleIncorrectCredentialsOrUnknownAccountException(){
        Meta meta = new Meta("用户名或密码错误", 401);
        return new ResponseEntity(null,meta);
    }

    @ExceptionHandler(LockedAccountException.class)
    public ResponseEntity handleLockedAccountException(LockedAccountException lae){
        Meta meta = new Meta(lae.getMessage(), 401);
        return new ResponseEntity(null,meta);
    }

    @ExceptionHandler(AuthenticationException.class)
    public ResponseEntity handleAuthenticationException(AuthenticationException ae){
        Meta meta = new Meta(ae.getMessage(), 401);
        return new ResponseEntity(null,meta);
    }

    @ExceptionHandler(UnauthorizedException.class)
    public ResponseEntity handleUnauthorizedException(UnauthorizedException ue){
        Meta meta = new Meta("您没有权限进行该操作，请联系系统管理员", 403);
        return new ResponseEntity(null,meta);
    }

    @ExceptionHandler(ParamException.class)
    public ResponseEntity handleParamException(ParamException pe){
        Meta meta = new Meta(pe.getMessage(), 400);
        return new ResponseEntity(null,meta);
    }

    @ExceptionHandler(RightException.class)
    public ResponseEntity handleRightException(RightException re){
        Meta meta = new Meta("您没有权限进行该操作，请联系开发人员", 403);
        return new ResponseEntity(null,meta);
    }
}
